package cn.cj.erp.serviceimpl.system;

import cn.cj.erp.common.enums.YesNoEnum;
import cn.cj.erp.common.utils.Convert;
import cn.cj.erp.common.utils.id.IdGenerator;
import cn.cj.erp.bo.system.SysNoticeBo;
import cn.cj.erp.bo.system.SysNoticeUserReadBo;
import cn.cj.erp.service.system.SysNoticeService;
import cn.cj.erp.service.system.SysNoticeUserReadService;
import cn.cj.erp.serviceimpl.base.ServiceImpl;
import cn.hutool.core.collection.CollectionUtil;
import cn.cj.erp.common.enums.StatusEnum;
import cn.cj.erp.entity.system.SysNotice;
import cn.cj.erp.dao.system.SysNoticeDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 通知公告表
 * @author chenjian
 */
@Slf4j
@Service
public class SysNoticeServiceImpl extends ServiceImpl<SysNotice, SysNoticeBo>
        implements SysNoticeService {
    @Resource
    private SysNoticeDao sysNoticeDao;
    @Resource
    private SysNoticeUserReadService sysNoticeUserReadService;

    @Override
    public SysNoticeDao getBaseMapper() {
        return sysNoticeDao;
    }

    @Override
    public SysNotice convert2Entity(SysNoticeBo sysNoticeBo) {
        return Convert.convert(sysNoticeBo, SysNotice.class);
    }

    @Override
    public SysNoticeBo convert2Bo(SysNotice sysNotice) {
        return Convert.convert(sysNotice, SysNoticeBo.class);
    }

    /**
     * 获取用户未读公告
     * @param userId 用户ID
     * @return 未读公告
     */
    @Override
    public List<SysNoticeBo> listByUserId(Long userId) {
        List<SysNotice> list = getBaseMapper().listByUserId(userId);
        return convert2BoList(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setUserRead(Long userId, List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return true;
        }
        for (Long id : ids) {
            SysNoticeUserReadBo userRead = sysNoticeUserReadService.getUserRead(userId, id);
            if (userRead == null) {
                userRead = SysNoticeUserReadBo.newInstance(userId, IdGenerator.generateId());
                sysNoticeUserReadService.save(userRead);
            } else {
                userRead.setReadStatus(YesNoEnum.YES);
                userRead.setStatus(StatusEnum.NORMAL);
                userRead.setModifyTime(new Date());
                sysNoticeUserReadService.updateById(userRead);
            }
        }
        return true;
    }
}